import { IPSAppView, IPSAppViewNavContext, IPSAppViewNavParam } from "@ibiz/dynamic-model-api"

/**
 * 上下文参数
 *
 * @interface ContextParam
 */
interface ContextParam {
  [key: string]: unknown
}

/**
 * 数据源
 *
 * @interface Data
 */
interface Data {
  [key: string]: unknown
}

/**
 * 计算自定义上下文参数
 *
 * @export
 * @param {IPSAppView} viewInstance
 * @param {...Data[]} args
 * @return {*}  {ContextParam}
 */
export function calcContext(viewInstance: IPSAppView, ...args: Data[]): ContextParam {
  const customViewNavContexts = viewInstance.getPSAppViewNavContexts()
  const contextParam: ContextParam = {}
  if (customViewNavContexts && customViewNavContexts.length > 0) {
    customViewNavContexts.forEach(item => {
      handleCustomViewParam(item, args, contextParam)
    })
  }
  return contextParam
}

/**
 * 处理自定义视图参数
 *
 * @export
 * @param {(IPSAppViewNavContext | IPSAppViewNavParam)} item
 * @param {Data[]} args
 * @param {ContextParam} contextParam
 */
export function handleCustomViewParam(item: IPSAppViewNavContext | IPSAppViewNavParam, args: Data[], contextParam: ContextParam) {
  const key = item.key.toLowerCase()
  if (item.rawValue) {
    // 直接赋值
    contextParam[key] = item.value
  }else {
    // 根据数据源列表，从后往前依次在对应的数据源中查找对应的变量值，找到则赋值并且返回
    // 未找到则赋予null
    const customKey = item.value.toLowerCase()
    for(let i = args.length - 1; i >= 0; i--) {
      const data = args[i]
      const value = data[customKey]
      if(value || value === 0 || value === false) {
        contextParam[key] = value
        return
      }
    }
    contextParam[key] = null
  }
}
